package com.itheima.controller;

import com.github.pagehelper.Page;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.entity.ResultMessage;
import com.itheima.pojo.Todo;
import com.itheima.service.ToDoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author hrz
 * @version 1.0
 * @date 2020-08-03 19:50
 */
@RestController
@RequestMapping("/todo")
@CrossOrigin(allowCredentials="true", allowedHeaders="*", methods={RequestMethod.GET,RequestMethod.POST}, origins="*")
public class ToDoController {
    @Autowired
    private ToDoService toDoService;
            
    // 增加代办事项
    @PostMapping("/add")
    public Result addToDo(@RequestBody Todo todo) {
        String addResult = toDoService.add(todo);
        if ("failed".equals(addResult)) {
            return new Result("error", "插入失败");
        }

        return new Result("success","插入成功");
    }
    
    // 删除代办事项
    @RequestMapping("/delete")
    public Result deleteToDo(@RequestBody Todo todo) {
        String deleteResult = toDoService.delete(todo);
        if ("failed".equals(deleteResult)) {
            return new Result("error", "删除失败");
        }
        return new Result("success","删除成功");
    }
    
    // 编辑代办事项
    @RequestMapping("/edit")
    public ResultMessage ediTodo(@RequestBody Todo todo) {
        String editResult = toDoService.eidt(todo);
        if ("failed".equals(editResult)) {
            return new ResultMessage(0,"error","操作失败");
        }
        return new ResultMessage(1,"success","操作成功");
    }
    
    @RequestMapping("/getList")
    public Result getLisTodo(@RequestBody Map<String, Object> searchMap) {
        Page<Todo> pageList = toDoService.getPageList(searchMap);
        com.itheima.entity.Page page = new com.itheima.entity.Page();
        
        page.setCurrent((Integer) searchMap.get("currentPage"));
        page.setRecords(pageList.getResult());
        page.setTotal((int) pageList.getTotal());
        
        return new Result("success", page);
    }
}
